/*
 * np_sem.h
 *
 *  Created on: Dec 8, 2010
 *      Author: jeff_zheng
 *   Copyright: NetPerform Technology
 */

#ifndef NP_SEM_H_
#define NP_SEM_H_

#include "pthread.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct np_mutex_s
{
	pthread_mutex_t	m;
}np_mutex;


static inline np_mutex* np_mutex_create()
{
	np_mutex* p_m = (np_mutex*)malloc(sizeof(np_mutex));
	pthread_mutexattr_t attr;
	if(0!=pthread_mutexattr_init(&attr))
	{
		free(p_m);
		return NULL;
	}
	if(0!=pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP))
	{
		free(p_m);
		return NULL;
	}
	if(0!=pthread_mutex_init(&p_m->m, &attr))
	{
		free(p_m);
		return NULL;
	}
	pthread_mutexattr_destroy(&attr);
	return p_m;
}
static inline int np_mutex_destroy(np_mutex* p_m)
{
	pthread_mutex_destroy(&p_m->m);
	free(p_m);

	return 0;
}

static inline int np_mutex_lock(np_mutex* p_m)
{
	int r = pthread_mutex_lock(&p_m->m);
	if(r!=0)
	{
		fprintf(stderr,"Failed to lock mutext, %s\n", strerror(errno));
	}
	return r;
}
static inline int np_mutex_unlock(np_mutex* p_m)
{
	int r = pthread_mutex_unlock(&p_m->m);
	if(r!=0)
	{
		fprintf(stderr,"Failed to unlock mutext, %s\n", strerror(errno));
	}
	return r;}

#ifdef __cplusplus
}
#endif

#endif /* NP_SEM_H_ */
